import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api/v1',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('Response Error:', error)
    const message = error.response?.data?.detail || error.message || '网络错误'
    return Promise.reject(new Error(message))
  }
)

export const chatApi = {
  // 流式聊天 - 优化版本
  async streamChat(content, sessionId, onChunk, onComplete) {
    try {
      const response = await fetch('/api/v1/chat/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content,
          session_id: sessionId
        })
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const reader = response.body?.getReader()
      if (!reader) {
        throw new Error('无法获取响应流')
      }

      const decoder = new TextDecoder()
      let buffer = ''
      let accumulatedContent = ''
      let currentMetadata = null
      let isInThinkingMode = false
      let thinkingContent = ''
      let actualContent = ''

      while (true) {
        const { done, value } = await reader.read()
        
        if (done) break

        buffer += decoder.decode(value, { stream: true })
        
        // 处理SSE数据
        const lines = buffer.split('\n')
        buffer = lines.pop() || '' // 保留不完整的行

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6).trim()
            
            if (data === '[DONE]') {
              // 流结束，调用完成回调
              if (onComplete) {
                onComplete({
                  content: accumulatedContent,
                  thinkingContent,
                  actualContent,
                  metadata: currentMetadata,
                  isComplete: true
                })
              }
              return
            }

            try {
              const chunk = JSON.parse(data)
              
              // 处理数据块
              if (chunk.type === 'data' && chunk.content) {
                const chunkContent = chunk.content
                accumulatedContent += chunkContent
                
                // 检测思考标签
                if (chunkContent.includes('<think>')) {
                  isInThinkingMode = true
                }
                
                if (isInThinkingMode) {
                  thinkingContent += chunkContent
                  
                  // 检测思考结束
                  if (chunkContent.includes('</think>')) {
                    isInThinkingMode = false
                    // 提取纯思考内容（去除标签）
                    const thinkMatch = thinkingContent.match(/<think>([\s\S]*?)<\/think>/i)
                    if (thinkMatch) {
                      thinkingContent = thinkMatch[1].trim()
                    }
                  }
                } else {
                  // 不在思考模式，累积实际回答内容
                  actualContent += chunkContent
                }
                
                // 更新元数据
                if (chunk.metadata) {
                  currentMetadata = chunk.metadata
                }
                
                // 调用块处理回调
                onChunk({
                  type: 'data',
                  content: chunkContent,
                  accumulatedContent,
                  thinkingContent: isInThinkingMode ? thinkingContent : thinkingContent.replace(/<\/?think>/gi, '').trim(),
                  actualContent: actualContent.replace(/<\/?think>/gi, '').trim(),
                  metadata: currentMetadata,
                  isComplete: false,
                  isInThinkingMode
                })
              }
            } catch (e) {
              console.warn('解析SSE数据失败:', data, e)
            }
          }
        }
      }
      
      // 如果没有收到 [DONE] 标记，也要调用完成回调
      if (onComplete) {
        onComplete({
          content: accumulatedContent,
          thinkingContent: thinkingContent.replace(/<\/?think>/gi, '').trim(),
          actualContent: actualContent.replace(/<\/?think>/gi, '').trim(),
          metadata: currentMetadata,
          isComplete: true
        })
      }
    } catch (error) {
      console.error('Stream chat error:', error)
      throw error
    }
  },

  // 获取历史消息
  async getHistory(sessionId) {
    return api.post(`/saver/messages/${sessionId}`)
  },

  // 存储历史记录
  async saveHistory(namespace, key, value) {
    return api.post('/store/history', {
      namespace,
      key,
      value
    })
  },

  // 获取存储的数据
  async getStored(namespace, key) {
    return api.get(`/store/get/${namespace}/${key}`)
  },

  // 删除存储的数据
  async deleteStored(namespace, key) {
    return api.delete(`/store/delete/${namespace}/${key}`)
  }
}

export default api